/*
 * @Description: NCTable快捷键(enter/up/down)
 * @Author: llixxm
 * @Date: 2019-08-12 14:19:47
 */

/**
 * @desc 查找下一个可聚焦元素
 * @param target {dom} 事件源
 * @param ViewModel {object} 全局变量
 * @param moduleId {string} 当前区域Id
 */
function onEnter(eventTarget, ViewModel, moduleId) {
    var parentTd = findParentTd(eventTarget);
    var nextTd = parentTd.nextElementSibling;
    var currentTr = nextTd.parentElement;
    var lastTd = findLastTdInRow(currentTr);
    var div = nextTd.querySelector('input[tabindex="0"]');
    
    //如果是最后一个元素就需要判断
    if (lastTd === nextTd) {
        var lastTr = currentTr.parentElement.lastElementChild;
        
        if(currentTr !== lastTr){
          findNextRowTd({ tr: currentTr, ViewModel, moduleId });
        }
        return;
    }

    // 如果下一个元素没有找到就继续查找
    if (div === null) {
        findNextSiblings({ td: nextTd, ViewModel, moduleId });
        return;
    }

    executeAutoFocus({ div, ViewModel });
}

function findParentTd(el) {
    while (el.parentElement) {
        el = el.parentNode;
        if (el.tagName === 'TD') {
            return el;
        }
    }
    return null;
}

/**
 * @desc 查找当前行里的最后一个td，需要排除操作列
 * @param tr {dom}
 * @return td {dom}
 */
function findLastTdInRow(tr) {
    let td = tr.lastElementChild.className.includes('fixed')
      ? tr.lastElementChild.previousElementSibling
      : tr.lastElementChild;

    return td;
}

/**
 * @desc 递归查找下一个可聚焦元素
 * @param td {dom} 上一个td
 * @param ViewModel {object} 全局变量
 * @param moduleId {string} 当前区域的Id
 */
function findNextSiblings({ td, ViewModel, moduleId }) {
  var nextTd = td.nextElementSibling;
  var currentTr = nextTd && nextTd.parentElement;
  var lastTd = currentTr && findLastTdInRow(currentTr);

  var div = nextTd && nextTd.querySelector('input[tabindex="0"]');

  if (lastTd === nextTd) {
      findNextRowTd({ tr: currentTr, ViewModel, moduleId });
      return;
  }

  if (div === null) {
      findNextSiblings({ td: nextTd, ViewModel, moduleId });
      return;
  }

  executeAutoFocus({ div, ViewModel });
}

//查找下一行可聚焦元素
function findNextRowTd({ tr, ViewModel, moduleId }) {
    var nextTr = tr.nextElementSibling;

    //如果是最后一行就查找下个区域的第一个可聚焦元素
    if (nextTr === null) {
      // isScrollToBottom(moduleId) ? '' : autoScroll(tr)
      // jumpToNextModuleFocusItem({ currentModuleId: moduleId, ViewModel });
      return;
    }
    autoScroll(nextTr).then(() => {
      var div = nextTr.querySelector('td input[tabindex="0"]');

      if (div === null) {
        findNextRowTd({ tr: nextTr, ViewModel, moduleId })
        return
      }

      executeAutoFocus({ div, ViewModel });
    })
}

/**
 * @desc 按上、下键查找下一个可聚焦元素
 * @param e {dom} 事件源
 * @param cellId {string} 单元格id
 */
function onArrowUpDown(e, cellId, moduleId) {
    let keycode = ''
    if(e.keyCode=='38'|| e.key === "ArrowUp"){
      keycode = 'ArrowUp'
    } else {
      keycode = 'ArrowDown'
    }

    var parentTd = findParentTd(e.currentTarget);
    var currentTr = parentTd.parentElement;
    findNextTdInColumn(currentTr, keycode, cellId, moduleId)
}

/**
 * @desc 获取下一个元素
 * @param currentTr {dom} 事件源
 * @param keycode {string} 快捷键（向上/向下）
 * @param cellId {string} 单元格id
 */
function findNextTdInColumn(currentTr, keycode, cellId, moduleId) {
    var nextTr = keycode === 'ArrowDown' ? currentTr.nextElementSibling : currentTr.previousElementSibling
    if(nextTr === null) {
      return;
    }

    let nextId = getNextCellId(keycode, cellId)
    let nextColumn = document.getElementById(nextId);
    autoScroll(nextTr, keycode, nextId).then(() => {
      let div = nextColumn ? nextColumn.querySelector('input[tabindex="0"]') : null;

      if(div === null){
        findNextTdInColumn(nextTr, keycode, nextId, moduleId);
        return;
      }
      executeAutoFocus({ div, ViewModel });
    })
    
    
}

/**
 * @desc 获取下一个元素id
 */
function getNextCellId(keycode, cellId) {
    let idArr = cellId.split('-');
    if(keycode === "ArrowUp"){ //箭头上
      if(idArr[4]>0){
          idArr[4]=idArr[4]-1;
      }
    }else if(keycode === "ArrowDown"){ //箭头下
        idArr[4]=idArr[4]-0+1;
    }
    return idArr.join('-');
}

/**
 * @desc 判断滚动条是否已滚动到底部
 */
function isScrollToBottom(moduleId){  
  let tableCon = document.querySelector(`div[fieldid=${moduleId}_table]`)
  let tableBodyScroll = tableCon.querySelector('.u-table-scroll').firstElementChild.lastElementChild
  return tableBodyScroll.scrollTop + tableBodyScroll.clientHeight === tableBodyScroll.scrollHeight
}

/**
 * @desc 判断滚动条是否需要滚动
 */
function autoScroll(nextTr, keycode, cellId){
  let tableBodyScroll = nextTr.parentElement.parentElement.parentElement;
  let cHeight = tableBodyScroll.clientHeight
  let diffHeight = Math.abs(nextTr.offsetTop - tableBodyScroll.scrollTop)
  return new Promise((resolve, reject) => {
    // if(keycode==='ArrowUp' && diffHeight<=40){
    //     tableBodyScroll.scrollTop = nextTr.offsetTop - cHeight + 31
    // } 
    // if(keycode!=='ArrowUp' && cHeight - diffHeight <= 31){
    //     tableBodyScroll.scrollTop = nextTr.offsetTop - cHeight/4
    // }
    resolve(true)
  })
  
}

function executeAutoFocus({ div, ViewModel }) {
    if (div !== null) {
      ViewModel.shouldAutoFocus = true;
      div.ncExecuteFocus = true;
      div.focus();
      div.select();
      delete div.ncExecuteFocus;
    }
}

//失去焦点
function autoBlur(){
  let activeEle = document.activeElement
  if(activeEle !== null){
    activeEle.blur()
  }
}
  
export {
      onEnter, onArrowUpDown, autoBlur
};